package it.giuseppetrisciuoglio.lyrics.service.expandurl;

import it.giuseppetrisciuoglio.lyrics.http.HttpReader;
import it.giuseppetrisciuoglio.lyrics.service.AbstractJsonService;
import it.giuseppetrisciuoglio.lyrics.service.expandurl.model.Response;

import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ExpandUrlService extends AbstractJsonService<Response> {

	@Autowired
	private HttpReader httpReader;
	
	private final String ENDPOINT_URL = "http://api.longurl.org/v2/expand?format=json&all-redirects=1&url=";
	
	private final transient Logger log = LoggerFactory.getLogger(getClass());
	
	public String getURL(String url) {
		log.debug("getURL(): url={}", url);
		try {
			String jsonResponse = httpReader.getResponse(ENDPOINT_URL + URLEncoder.encode(url, "UTF-8"));
			Response response = parseJson(jsonResponse, Response.class);
			log.debug("getURL(): response={}", response);
			if (response != null){
				return response.getLongUrl();
			}
		} catch (Exception e) {
			log.warn("getURL(): error try a expandurl for this '{}'", url);
		}
		return null;
	}

}
